<?php

namespace App\Http\Controllers;

use App\Models\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use GuzzleHttp\Client;

class CommonController extends Controller
{

    //获取openid
    public function getOpenid(Request $request){
        $uid = $request->get('uid');
        Log::info('weixin getOpenid start uid : '.$uid);
        $user = Users::where('id',$uid)->first();
        $code = $request->get('code', '');  # redirect_uri/?code=CODE&state=STATE
//        dd(route('api.common.openid',array('uid'=>1)));
        Log::info('weixin getOpenid start code : '.$code);
        // 用户在微信中, 并且没有关联 openid
        if ($code) {
            // 通过 code 获取 open_id
            Log::info('weixin oauth2:'.$code);
            $client = new Client();
            $url = sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                env('WEIXIN_KEY'), env('WEIXIN_SECRET'), $code);
            try {
                $res = $client->request('GET', $url, ['timeout' => 1.5]);
                $res = $res->getBody();
                Log::info('weixin oauth2:'.$res);
                $res = json_decode($res);

                $user->openid = $res->openid;
                $user->save();
            } catch(\Throwable $e) {
                Log::error('Fail to call api');
            }
        }
        return ;
    }

}
